#coding=utf-8
import numpy as np
import pandas as pd
import talib as ta 
# 这个是聚宽网(joinquant)的数据下载API，免费账户每天能下载100万条数据
from jqdatasdk import *
import matplotlib.pyplot as plt
from jqdatasdk.api import get_price

# 登录验证
auth("15618398061", "@Liliwang99")

hs300id="000300.XSHG"
pabid='000001.XSHE'
# 下载2015-2018年的沪深300指数，频率为每天，只要收盘价
price = get_price(pabid, start_date="2017-12-01", end_date="2018-12-31", frequency="daily", fields=['close'])
close = price['close']

# 找出n天后收益率大于p值的序列
# 计算3天的收益率
ret3 = close.pct_change(periods=3)
# 找出大于p的收益率信号
ret3_2_sig=(ret3>=0.02)
# 得到信号
#ret3_2_sig=ret3_2_b * ret3
print(ret3_2_sig.describe())

# 采用和国内一致的算法
ta.set_compatibility(1)
# 用talib库中的相应函数计算MACD指标
dif, dea, hist = ta.MACD(close)
# 计算EMA12和EMA26
ema12 = ta.EMA(close, 12)
ema26 = ta.EMA(close, 26)

# 画图
plt.figure(figsize=(18,12))
#价格
ax1=plt.subplot(4,1,1)
ax1.plot(close)
# n天收益率
ax2=plt.subplot(4,1,2)
ax2.bar(x=ret3.index, height=ret3.values)
# 大于2%的信号
ax3=plt.subplot(4,1,3)
ax3.bar(x=ret3_2_sig.index, height=ret3_2_sig.values)
# macd 
ax4=plt.subplot(4,1,4)
ax4.plot(dif,color='orange')
ax4.plot(dea,color='red')
ax4.bar(x=hist.index, height=hist.values*2,color='green')
plt.legend(["dif", "dea", "hist"], loc="upper left")
plt.show()